package ${domain}.task;

import ${domain}.frame.auth.LocalData;
import ${domain}.frame.schedule.RunDelayRepeatTask;
import ${domain}.frame.utils.SqlUtil;
import ${domain}.module.wsys.mgr.LogerrManager;
import ${domain}.module.wsys.mgr.TokensManager;
import ${domain}.module.wsys.req.TokensLogoutRequest;
import ${domain}.module.wsys.rsp.TokensLogoutResponse;

import java.time.Duration;
import java.util.Date;
import java.util.List;

public class TokenTask extends RunDelayRepeatTask {

    @Override
    public String taskId() {
        return "1";
    }

    @Override
    public String taskName() {
        return "登录凭证处理任务";
    }

    @Override
    public String taskNote() {
        return "处理过期登录凭证状态，及时注销。";
    }

    @Override
    public Duration interval() {
        return Duration.ofMinutes(1);
    }

    @Override
    protected void task() {
        TokensManager tokensManager = LocalData.getBean(TokensManager.class);
        LogerrManager logerrManager = LocalData.getBean(LogerrManager.class);
        if (tokensManager == null) {
            return;
        }
        List<TokensLogoutRequest> select = SqlUtil.select("SELECT TOKEN FROM SYS_TOKENS WHERE VALID = '1' AND IS_DELETED = '0' AND VALID_TIME < " + new Date().getTime(), TokensLogoutRequest.class);
        for (TokensLogoutRequest request : select) {
            TokensLogoutResponse tokensLogoutResponse = tokensManager.logout(request, LocalData.getSysToken());
            if (tokensLogoutResponse.hasError()) {
                logerrManager.addErr("任务错误", "登录凭证注销错误", tokensLogoutResponse.getErrors().get(0).getMessage());
            }
        }
    }
}
